/**
 * 
 */
package org.oy.sealogger.parser;

import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;
import org.oy.sealogger.common.Config;
import org.oy.sealogger.ds.nmea.NMEA0183DataSource;
import org.oy.sealogger.route.GPSLocation;

/**
 * @author Juho Heikka
 *
 */
public class CurrentState 
			extends Observable 
			implements Runnable, Observer {
	
	private static CurrentState instance = null;
	
	/** 
	 * Observers will be update if this is true 
	 * */
	boolean running;
	
	private Logger log = Config.getLogger();
	
	RMCSentence rmcSentence;
	GSASentence gsaSentence;
	
	/** Observers will be updated if state has changed during this interval
	 *  interval is in milliseconds 
	 *  */
	int updateInterval = 2000;
	
	private CurrentState() {
		rmcSentence = new RMCSentence();
		gsaSentence = new GSASentence();
		running = true;

		Thread t = new Thread(this);
		t.start();
	}
	
	public static CurrentState getInstance() {
		if(instance == null)
			instance = new CurrentState();
		
		return instance;
	}
	
	public void run() 
	{
		while (running) 
		{
			if (hasChanged()) {
				notifyObservers();			
			}
			
			//available = new Semaphore(countObservers(), true);
			try {
				Thread.sleep(updateInterval);
			} catch (InterruptedException ie) {
				System.out.print(ie);
			}
		}
	}

	public RMCSentence getGPSLocation()
	{
		return rmcSentence;
	}

	public double getLatitude() {
		return rmcSentence.getLatitudeAsDouble();
	}
	
	public double getLongitude() {
		return rmcSentence.getLongitudeAsDouble();
	}
	
	public int getActiveSatelliteCount() {
		return gsaSentence.countActiveSatellites();
	}
	
	public void update(Observable obs, Object data) {
		
		String strData = data instanceof String ? (String)data : null;
		boolean changed = true;
		
		if(obs instanceof NMEA0183DataSource && strData.substring(3).startsWith("RMC"))
			rmcSentence.addSentence(strData);
			
		else if(obs instanceof NMEA0183DataSource && strData.substring(3).startsWith("GSA"))
			gsaSentence.addSentence(strData);
		else
			changed = false;
		
		if(changed)
			setChanged();
		
	}
	
}
